package com.xyj.week01;

/**
 * 找到链表的倒数第K个元素
 */
public class T6 {

    public static void main(String[] args) {
        //初始化环形链表
        Node node = new Node(5);
        Node node1 = new Node(6);
        Node node2 = new Node(7);
        Node node3 = new Node(8);
        Node node4 = new Node(4);
        node.next=node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        System.out.println(findTheLastK(node, 2));
    }


    public static Node findTheLastK(Node head,Integer k){
        Node slow = head;
        Node fast = head;
        //快指针先走k步
        while (k-->0){
            fast=fast.next;
        }
        //快指针和慢指针一起走
        // 当快指针走到最后一个位置时，慢指针走到倒数第k个位置
        while (fast!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;


    }
}
